﻿using Microsoft.EntityFrameworkCore;
using NewFormatProject.Infrastructure.Atrributes;
using NewFormatProject.Infrastructure.Dto.Datas;
using NewFormatProject.Infrastructure.Dto.Requests.Objects;
using NewFormatProject.Infrastructure.Dto.Responses;
using NewFormatProject.Infrastructure.Dto.Responses.Objects;
using NewFormatProject.Infrastructure.EFCore;
using NewFormatProject.Infrastructure.Tools;
using NewFormatProject.Server.EFCore;
using NewFormatProject.Server.Instances.Extends.Entitys;
using NewFormatProject.Server.Instances.Extends.Requests;
using NewFormatProject.Server.Interfaces;
using System.Collections.Generic;
using System.IO;
using System.IO.Enumeration;
using System.Linq;
using System.Threading.Tasks;

namespace NewFormatProject.Server.Instances
{
    internal class UserIOC
    {
        public SysUserServerEF sysUserServerEF { get; set; }
    }
    [InjectClass]
    public class UserServer : IUserServer
    {
        private readonly UserIOC _userIOC;
        private readonly DbContext _dbContext;
        public UserServer(DbContext dbContext)
        {
            _dbContext= dbContext;
            _userIOC = new UserIOC
            {
                sysUserServerEF = new SysUserServerEF(dbContext),
            };
        }

        public async Task<ResponseApiDto> Add(RequestSysUsersDto dto)
        {
            SysUsers user = dto.ToEntity();
            user.USalt = Tools.Guid_1();
            user.UPassword = Encrypt.GetMd5Hash(user.UPassword + user.USalt);
            return ResponseApiDto.Create(await _userIOC.sysUserServerEF.Add(user));
        }

        public async Task<ResponseApiDto> Delete(RequestSysUsersDto dto)
        {
            return ResponseApiDto.Create(await _userIOC.sysUserServerEF.Delete(dto.ToEntity()));
        }

        public async Task<ResponseApiDto> Detail(int id)
        {
            return ResponseApiDto.Success("数据已获取", (await _userIOC.sysUserServerEF.Query(d => d.UId == id).SingleOrDefaultAsync()).ToResponseDto(_dbContext));
        }

        public SysUsers Find(int id)
        {
            return _userIOC.sysUserServerEF.Query(d => d.UId == id).SingleOrDefault();
        }

        public async Task<ResponseApiDto> Pagination(int page, int limit, string key)
        {
            List<ResponseSysUsersDto> result = new List<ResponseSysUsersDto>();
            int total = 0;
            List<SysUsers> users = await _userIOC.sysUserServerEF.Pagination1(d => string.IsNullOrEmpty(key) || d.UName.Contains(key), false, d => d.UCreateTime, out total, page, limit).ToListAsync();
            users.ForEach(user =>
            {

                result.Add(user.ToResponseDto(_dbContext));
            });
            return ResponseApiDto.Success("数据已获取", new PaginationData
            {
                data = result,
                total = total
            });
        }

        public async Task<ResponseApiDto> UpdateWithImage(RequestSysUsersDto dto)
        {
            if (!Exist(dto.id))
            {
                return ResponseApiDto.Fail("用户不存在");
            }
            var newUser = dto.ToEntity();
            if (dto.avatarImage != null)
            {
                // 修改图片
                var user = _userIOC.sysUserServerEF.Query(d => d.UId == dto.id).Single();
                var fileName = await Tools.UploadImage(dto.avatarImage, Path.Combine(Tools.GetUploadImagePath(), dto.id.ToString()));
                // 修改用户
                if (fileName != null)
                {
                    newUser.UAvatar = fileName;
                    if (!string.IsNullOrEmpty(user.UAvatar))
                    {
                        Tools.DeleteImage(Path.Combine(Tools.GetUploadImagePath(), dto.id.ToString(), user.UAvatar));
                    }
                }
            }
            else
            {
                newUser.UAvatar = null;
            }
            return ResponseApiDto.Create(await _userIOC.sysUserServerEF.UpdateAllProperNotNull(newUser));
        }
        public async Task<ResponseApiDto> UpdateWithoutImage(RequestSysUsersDto dto)
        {
            if (!Exist(dto.id))
            {
                return ResponseApiDto.Fail("用户不存在");
            }
            return ResponseApiDto.Create(await _userIOC.sysUserServerEF.UpdateAllProperNotNull(dto.ToEntity()));
        }
        private bool Exist(int id)
        {
            return _userIOC.sysUserServerEF.Query(d => d.UId == id).Any();
        }

        public async Task<int> Update(SysUsers dto)
        {
            return await _userIOC.sysUserServerEF.UpdateAllProper(dto);
        }
    }
}
